﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;

namespace WPFCustomControlExample
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            LoadSkin();

            FrameworkElement.DataContextProperty.OverrideMetadata(typeof(DataGrid),
                new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits, new PropertyChangedCallback(OnDataContextChanged)));
        }

        public static void OnDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            DataGrid grid = d as DataGrid;
            if (grid == null)
            {
                return;
            }

            foreach (DataGridColumn col in grid.Columns)
            {
                DependencyObject header = col.Header as DependencyObject;
                if (header == null)
                {
                    continue;
                }

                header.SetValue(FrameworkElement.DataContextProperty, e.NewValue);
            }
        }

        private void LoadSkin()
        {
            try
            {
                string source = "pack://application:,,,/Themes;component/DefaultTheme.xaml";

                //清除现有资源 
                Current.Resources.MergedDictionaries.Clear();

                ResourceDictionary resource = new ResourceDictionary()
                {
                    Source = new Uri(source, UriKind.Absolute)
                };

                //将资源字典合并到当前资源中
                Current.Resources.MergedDictionaries.Add(resource);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
